package eoeProject.edenOfEast.page.analyses.analysesTop.component;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;

import org.apache.wicket.AttributeModifier;
import org.apache.wicket.ajax.AjaxRequestTarget;
import org.apache.wicket.ajax.markup.html.form.AjaxButton;
import org.apache.wicket.markup.html.WebPage;
import org.apache.wicket.markup.html.basic.Label;
import org.apache.wicket.markup.html.form.Form;
import org.apache.wicket.markup.html.form.ListChoice;
import org.apache.wicket.markup.html.form.TextField;
import org.apache.wicket.markup.html.link.BookmarkablePageLink;
import org.apache.wicket.markup.html.list.ListItem;
import org.apache.wicket.markup.html.list.ListView;
import org.apache.wicket.markup.html.panel.Panel;
import org.apache.wicket.model.AbstractReadOnlyModel;
import org.apache.wicket.model.Model;
import org.apache.wicket.request.mapper.parameter.PageParameters;

import eoeProject.edenOfEast.bean.EOEAnalysesBean;
import eoeProject.edenOfEast.core.DBConnector;
import eoeProject.edenOfEast.core.SQLExp;
import eoeProject.edenOfEast.core.SQLMaker;
import eoeProject.edenOfEast.dataBase.DB_EOE_ANALYSES;
import eoeProject.edenOfEast.utils.AnalysesUtils;

//@AuthorizeInstantiation("ADMIN")
public class AnalysesTopSearchPanel extends Panel {
	private static final long serialVersionUID = 1L;

	final static Integer TITLE_MAX_LENGTH = 10;

	final static Integer ABOUT_MAX_LENGTH = 23;

	private Form<Void> form = new Form<Void>("searchForm");

	private Model<String> searchType = new Model<String>("キーワード検索");

	private Model<String> sortType = new Model<String>("作成日が新しい順");

	private Model<String> keyword = new Model<String>("");

	private Model<String> category = new Model<String>("");

	private List<EOEAnalysesBean> beanList = new LinkedList<EOEAnalysesBean>();

	private ListView<Object> searchResultList;

	@SuppressWarnings({ "rawtypes" })
	public AnalysesTopSearchPanel(String id) {
		super(id);

		List<String> typeSelectList = new ArrayList<String>();
		typeSelectList.add("キーワード検索");
		typeSelectList.add("タグ検索");
		typeSelectList.add("カテゴリ検索");
		ListChoice<String> searchTypeList = new ListChoice<String>(
				"searchTypeList", searchType, typeSelectList);
		form.add(searchTypeList);

		List<String> sortSelectList = new ArrayList<String>();
		sortSelectList.add("作成日が新しい順");
		sortSelectList.add("作成日が古い順");
		sortSelectList.add("レスが多い順");
		sortSelectList.add("レスが少ない順");
		ListChoice<String> searchSortList = new ListChoice<String>(
				"searchSortList", sortType, sortSelectList);
		form.add(searchSortList);

		ListChoice<String> categoryList = new ListChoice<String>(
				"searchCategoryList", category, AnalysesUtils.getCategoryList());
		form.add(categoryList);

		TextField<String> searchKeywordForm = new TextField<String>(
				"searchKeywordForm", keyword);
		form.add(searchKeywordForm);

		form.add(searchButton);
		add(form);

		searchResultList = new ListView<Object>("searchResultList", beanList) {
			private static final long serialVersionUID = -6962499153966966392L;

			@Override
			protected void populateItem(ListItem item) {

			}

		};

		searchResultList.setOutputMarkupId(true);
		add(searchResultList);

		Label searchResultExist = new Label("searchResultExist");
		searchResultExist.add(new AttributeModifier("style",
				new AbstractReadOnlyModel() {
					/**
					 *
					 */
					private static final long serialVersionUID = -8497484991143512281L;

					/**
			 *
			 */

					@Override
					public Object getObject() {
						return "color :#000000;";
					}
				}));
		add(searchResultExist);

	}

	private AjaxButton searchButton = new AjaxButton("searchButton") {
		/**
		 *
		 */
		private static final long serialVersionUID = -2942520388218435030L;

		@SuppressWarnings("rawtypes")
		@Override
		protected void onSubmit(AjaxRequestTarget target, Form form) {
			setResponsePage(form.getPage());

			beanList.clear();

			SQLMaker sql = new SQLMaker(DB_EOE_ANALYSES.TABLE_NAME,
					SQLMaker.SQL_TYPE_SELECT);

			SQLExp exp1 = new SQLExp();
			exp1.setExpEquals(DB_EOE_ANALYSES.STATUS, 1);
			if (searchType.getObject() == null
					|| searchType.getObject().equals("")
					|| searchType.getObject().equals("キーワード検索")) {
				SQLExp exp2 = new SQLExp();
				exp2.setExpLike(DB_EOE_ANALYSES.TITLE, keyword.getObject());
				SQLExp exp3 = new SQLExp();
				exp3.setExpLike(DB_EOE_ANALYSES.ABOUT, keyword.getObject());
				exp2.jointExpOr(exp3);
				exp1.jointExpAnd(exp2);
			} else if (searchType.getObject().equals("タグ検索")) {
				SQLExp exp2 = new SQLExp();
				exp2.setExpLike(DB_EOE_ANALYSES.TAG1, keyword.getObject());
				SQLExp exp3 = new SQLExp();
				exp3.setExpLike(DB_EOE_ANALYSES.TAG2, keyword.getObject());
				SQLExp exp4 = new SQLExp();
				exp4.setExpLike(DB_EOE_ANALYSES.TAG3, keyword.getObject());
				exp2.jointExpOr(exp3);
				exp2.jointExpOr(exp4);
				exp1.jointExpAnd(exp2);

			} else if (searchType.getObject().equals("カテゴリ検索")) {
				SQLExp exp2 = new SQLExp();
				exp2.setExpEquals(DB_EOE_ANALYSES.CATEGORY_ID,
						AnalysesUtils.getCategoryId(category.getObject()));
				exp1.jointExpAnd(exp2);
			}
			sql.setExp(exp1);
			if (sortType.getObject() == null || sortType.getObject().equals("")
					|| sortType.getObject().equals("作成日が新しい順")) {
				sql.addOrderBy(DB_EOE_ANALYSES.CREATE_DATE, "desc");
			} else if (sortType.getObject().equals("作成日が古い順")) {
				sql.addOrderBy(DB_EOE_ANALYSES.CREATE_DATE, "asc");
			} else if (sortType.getObject().equals("レスが多い順")) {
				sql.addOrderBy(DB_EOE_ANALYSES.TOTAL_RES, "desc");
			} else if (sortType.getObject().equals("レスが少ない順")) {
				sql.addOrderBy(DB_EOE_ANALYSES.TOTAL_RES, "asc");
			}

			sql.addLimit(10);
			ResultSet rs = DBConnector.getInstance().get(sql.getSQL());

			try {
				while (rs.next()) {
					EOEAnalysesBean bean = new EOEAnalysesBean();
					bean.setAnalysesId(rs.getInt(DB_EOE_ANALYSES.ANALYSES_ID));
					bean.setTitle(rs.getString(DB_EOE_ANALYSES.TITLE));
					bean.setCategoryId(rs.getInt(DB_EOE_ANALYSES.CATEGORY_ID));
					bean.setUpdateDate(rs
							.getTimestamp(DB_EOE_ANALYSES.UPDATE_DATE));
					bean.setAbout(rs.getString(DB_EOE_ANALYSES.ABOUT));

					beanList.add(bean);
				}
				rs.close();
			} catch (SQLException e) {
				System.out.println("AnalysesTopListPanelException: "
						+ e.getMessage());
			}

			searchResultList = new ListView<Object>("searchResultList",
					beanList) {
				private static final long serialVersionUID = -6962499153966966392L;

				@Override
				protected void populateItem(ListItem item) {
					final EOEAnalysesBean bean = (EOEAnalysesBean) item
							.getModelObject();

					PageParameters parameters = new PageParameters();
					parameters.add("analysesId", bean.getAnalysesId());
					BookmarkablePageLink<WebPage> link = new BookmarkablePageLink<WebPage>(
							"searchResultLink",
							eoeProject.edenOfEast.page.analyses.analysesRes.Index.class,
							parameters);
					String titleValue = bean.getTitle();
					if (titleValue.length() > TITLE_MAX_LENGTH) {
						titleValue = bean.getTitle().substring(0,
								TITLE_MAX_LENGTH - 1);
						titleValue = titleValue + "…";
					}
					link.add(new Label("searchResultTitle", titleValue));
					item.add(link);
					item.add(new Label("searchResultCategory", AnalysesUtils
							.getCategoryName(bean.getCategoryId())));
					SimpleDateFormat sdf = new SimpleDateFormat("M月d日 H時m分");
					item.add(new Label("searchResultUpdateDate", sdf
							.format(bean.getUpdateDate())));
					String aboutValue = bean.getAbout();
					if (aboutValue.length() > ABOUT_MAX_LENGTH) {
						aboutValue = bean.getAbout().substring(0,
								ABOUT_MAX_LENGTH - 1);
						aboutValue = aboutValue + "…";
					}
					item.add(new Label("searchResultAbout", aboutValue));
				}

			};
			searchResultList.setOutputMarkupId(true);

			Label searchResultExist = new Label("searchResultExist");
			searchResultExist.add(new AttributeModifier("style",
					new AbstractReadOnlyModel() {
						/**
				 *
				 */
						private static final long serialVersionUID = 3406851160722465174L;

						@Override
						public Object getObject() {
							return "color :#FFFFFF;";
						}
					}));
			searchResultExist.setOutputMarkupId(true);
			addOrReplace(searchResultExist);
			target.getPage().get("analysesTopPanel")
					.get("analysesTopSearchPanel").get("searchResultExist")
					.replaceWith(searchResultExist);
			target.getPage().get("analysesTopPanel")
					.get("analysesTopSearchPanel").get("searchResultList")
					.replaceWith(searchResultList);

		}

		@SuppressWarnings({ "rawtypes" })
		@Override
		protected void onError(final AjaxRequestTarget target, final Form form) {

		}
	};

}
